#include "LogAppender.h"
#include <iostream>
#include "utils/TimeUtil.h"

namespace log
{

void LogAppender::append(const LogEvent::ptr ptrEvent)
{
    if (nullptr != m_ptrLayout)
    {
        append(m_ptrLayout->format(ptrEvent));
    }
    else
    {
        append(ptrEvent->getMsg());
    }
}

FileAppender::FileAppender(const std::string& strFile)
{
    open(strFile);
}
    
FileAppender::~FileAppender()
{
    close();
}

bool FileAppender::open(const std::string& strFile)
{
    std::string file = strFile + utils::TimeUtil::getCurrentDateTime("%Y%m%d_%H%M%S") + ".log";
    m_ofstream.open(file, std::ios::app);
    m_strFile = strFile;
    m_ofstream.seekp(0, m_ofstream.end);
    m_nCurrSize = m_ofstream.tellp();
}

void FileAppender::close()
{
    if (m_ofstream.is_open())
    {
        m_ofstream.close();
    }
}

void FileAppender::setFileMaxSize(const std::string& n)
{
    m_nMaxSize = 0; 
    for (const char i: n)
    {
        if (i >= '0' && i <= '9')
        {
            m_nMaxSize = m_nMaxSize * 10 + (i-'0');
        }
        else
        {
            if (i == 'K' || i == 'k')
            {
                m_nMaxSize *= 1000; 
            }
            else if (i == 'M' || i == 'm')
            {
                m_nMaxSize *= 1000 * 1000; 
            }
            else if (i == 'T' || i == 't')
            {
                m_nMaxSize *= 1000 * 1000 * 1000; 
            }
            else
            {
                 
            }
        }
    }
}

void FileAppender::append(const std::string& strLog)
{
    m_ofstream << strLog;
    m_ofstream.flush();
    m_nCurrSize += strLog.size();
    if (m_nCurrSize > m_nMaxSize)
    {
        close();
        open(m_strFile);
    }
}

void StdoutAppender::append(const std::string& strLog)
{
    std::cout << strLog;
    std::cout.flush();
}

} // namespace log
